package utils

import (
	"fmt"
	"github.com/dsoprea/go-exif/v3"
	exifcommon "github.com/dsoprea/go-exif/v3/common"
	"io/ioutil"
	"os"
	"strings"
)

// 获取文件后缀
func GetFileExt(filename string) string {
	middleFileData := strings.Split(filename, ".")
	exp := middleFileData[len(middleFileData)-1]
	return exp
}

//判断目录是否存在
func DirExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}

	return false, err

}

//递归创建文件夹
func CreateDir(path string) error {
	if is, _ := DirExists(path); !is {
		err := os.MkdirAll(path, os.ModePerm)
		if err != nil {
			return err
		}
	}
	return nil
}

func ReadExifGps(path string) (lat float64, lng float64, alt int, err error) {
	//filepath := "tdy/upload/2022/7/12/65236db7-91b1-4c57-955a-b5160991ece8/65236db7-91b1-4c57-955a-b5160991ece8.JPG"
	rawExif, err := exif.SearchFileAndExtractExif(path)
	im, err := exifcommon.NewIfdMappingWithStandard()
	ti := exif.NewTagIndex()
	_, index, err := exif.Collect(im, ti, rawExif)
	ifd, err := index.RootIfd.ChildWithIfdPath(exifcommon.IfdGpsInfoStandardIfdIdentity)
	gi, err := ifd.GpsInfo()
	lat = gi.Latitude.Decimal()
	lng = gi.Longitude.Decimal()
	alt = gi.Altitude
	return
}

func GetFileType(contentType string) int {
	rs := strings.Split(contentType, "/")
	switch rs[0] {
	case "image":
		return 1
	case "audio":
		return 2
	case "video":
		return 3
	}
	return 0
}
func IsSupport(contentType string) bool {
	support := []string{"image/jpg", "image/jpeg", "image/png", "image/tiff"}
	for _, s := range support {
		if contentType == s {
			return true
		}
	}
	return false
}
func GetAllFile(pathname string) ([]string, error) {
	result := []string{}

	fis, err := ioutil.ReadDir(pathname)
	if err != nil {
		fmt.Printf("读取文件目录失败，pathname=%v, err=%v \n", pathname, err)
		return result, err
	}

	// 所有文件/文件夹
	for _, fi := range fis {
		fullname := pathname + "/" + fi.Name()
		// 是文件夹则递归进入获取;是文件，则压入数组
		if fi.IsDir() {
			temp, err := GetAllFile(fullname)
			if err != nil {
				fmt.Printf("读取文件目录失败,fullname=%v, err=%v", fullname, err)
				return result, err
			}
			result = append(result, temp...)
		} else {
			result = append(result, fullname)
		}
	}

	return result, nil
}
